﻿using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class BulkheadIsolation : DemoBase
    {
        public override string DemoName => "Polly-Bulkhead Isolation Demo";
        int resourceId = 0;

        public override void RunDemo()
        {
            base.Init();
            resourceId = 0;
            //制定策略最大的并发数为5
            Policy policyExecutes = Policy.Bulkhead(5);
            for (int i = 0; i < 50; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        policyExecutes.Execute(() =>
                        {
                            RequestFromWeb();
                        });
                    }
                    catch (Exception ex)
                    {
                        PrintErrorLog(ex.Message);
                        throw;
                    }
                });
            }
        }


        private void RequestFromWeb()
        {
            resourceId++;//模拟异常场景
            if (resourceId % 3 == 0)
            {
                throw new Exception($"请求数据包{resourceId}失败 请求过于频繁（报异常 但程序没崩溃哟）");
            }
            else
            {
                PrintSuccessLog($"请求数据包{resourceId}成功");
            }
        }
    }
}
